package com.zyplayer.doc.git.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCreator {


    public static void createZip(String sourceFolderPath, String destinationFilePath, List<String> blackList) {
        try {
            FileOutputStream fos = new FileOutputStream(destinationFilePath);
            ZipOutputStream zos = new ZipOutputStream(fos);
            File sourceFolder = new File(sourceFolderPath);

            addFilesToZip(sourceFolder, sourceFolder, blackList, zos);

            zos.closeEntry();
            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addFilesToZip(File sourceFolder, File currentFolder, List<String> blackList, ZipOutputStream zos) throws IOException {
        File[] files = currentFolder.listFiles();
        byte[] buffer = new byte[1024];
        int length;
        assert files != null;
        for (File file : files) {
            String fileName = file.getName();

            if (blackList.contains(fileName) || fileName.endsWith("zip")) {
                continue;
            }
            if (file.isDirectory()) {
                addFilesToZip(sourceFolder, file, blackList, zos); // 递归处理子文件夹
            } else {
                FileInputStream fis = new FileInputStream(file);
                ZipEntry zipEntry = new ZipEntry(file.getAbsolutePath().substring(sourceFolder.getAbsolutePath().length() + 1));
                zos.putNextEntry(zipEntry);

                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }

                fis.close();
            }
        }
    }

}